package com.hongshan.wallet.base

import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.support.v4.util.ArrayMap
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.hongshan.wallet.R
import kotlinx.android.synthetic.main.layout_empty_view.view.*


/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.base
 * @author   : zhangxx
 * @data     : 2019/3/21
 * @email    : qq957413212@hotmail.com
 */
abstract class BaseRecyclerAdapter : RecyclerView.Adapter<BaseViewHolder<MyViewModel>>() {

    var showEmpty = false

    val vmList = ArrayMap<Int, MyViewModel>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<MyViewModel> {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, viewType, parent, false)
        return BaseViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BaseViewHolder<MyViewModel>, position: Int) {
        if (!showEmpty) {
            vmList.remove(position)
            val obj = getViewModel(holder,position)
            vmList[position] = obj
            holder.bind(initVariableId(position), obj)
        }
        holder.itemView.llEmptyView?.setOnClickListener { refresh() }
    }

    override fun getItemViewType(position: Int) =
        if (showEmpty) R.layout.layout_empty_view else getLayoutIdForPosition(position)

    abstract fun getViewModel(holder: BaseViewHolder<MyViewModel>, position: Int): MyViewModel

    abstract fun getLayoutIdForPosition(position: Int): Int

    abstract fun initVariableId(position: Int): Int

    override fun getItemCount() = if (showEmpty) 1 else 0

    open fun isEmpty() = false

    fun showEmpty() {
        if (!showEmpty) {
            showEmpty = true
            notifyDataSetChanged()
        }
    }

    fun hideEmpty() {
        if (showEmpty) {
            showEmpty = false
            notifyDataSetChanged()
        }
    }

    open fun refresh() {}
}